// pages/order/order.js
const config = require('../../config/config')
const { checkLogin } = require('../../utils/util')
const app = getApp()
let intervalTime = 0 //保存订单页最近生成的定时器ID
Page({

    /**
     * 页面的初始数据
     */
    data: {
        TabCur: 0,
        tabList: config.myOrderTab(),
        pageInfo: '', //页面显示的错误信息
        order: [
        ], //所有的订单
        orderStatus: config.orderStatus,
    },
    //获取某种订单状态的订单
    async getOsByOStatus(status) {
        // if(!status)status='all'
        const { userInfo } = app.globalData
        console.log(userInfo)
        const flag = await checkLogin(userInfo)
        if (flag == 'unlogin') return
        wx.showLoading()
        wx.request({
            url: `${config.server}/order/getOrderByStatus`,
            data: {
                openid: userInfo.openid,
                status: status
            },
            success: res => {
                if (res.data.status == 'success') {
                    this.setData({
                        order: res.data.data
                    })
                    if (status == 'all' || status == 'unpay') {
                        //遍历order数组
                        this.data.order.forEach((item, i) => {
                            if (item.order_status === 'unpay') {
                                // countdown倒计时
                                this.countdown(i, item.order_add_time)
                            }
                        })
                    }
                }
                else {
                    wx.showToast({
                        title: '服务器异常',
                        icon: 'error'
                    })
                }
                wx.hideLoading()
            },
            fail: err => {
                wx.showToast({
                    title: '网络异常',
                    icon: 'error'
                })
                wx.hideLoading()
            }
        })
    },
    // 取消订单
    cancelOrder(e) {
        let {
            order
        } = this.data
        wx.showModal({
            title: '提示',
            content: '你确认取消当前订单吗?',
            success: res => {
                if (res.confirm) {
                    const {
                        index
                    } = e.currentTarget.dataset
                    this.updateOrder(index, 'status', 'cancel')
                    // order[index].order_status = 'cancel' //修改订单状态
                    clearInterval(order[index].intervalTime) //清除当前订单的计时器
                    // 更新data中的order
                    this.setData({
                        order
                    })
                    // // 刷新页面
                    // this.onShow()
                }
            },

        })
    },
    // 支付订单
    async handleOrder(e) {
        const {
            index,
            status
        } = e.currentTarget.dataset
        const {
            order
        } = this.data
        await this.updateOrder(index, 'status', status)
        clearInterval(order[index].intervalTime)
        //发送订单支付消息给admin
        if (status == 'payOk') {
            this.createSocket(app.globalData.userInfo.openid, order[index]._id)
        }
    },
    // 清除所有的定时器
    clearTime(timer) {
        for (let i = 0; i < timer; i++) {
            clearInterval(i)
        }
    },
    //倒计时
    countdown(index, addTime) {
        const that = this
        const endTime = new Date(addTime).getTime() / 1000 + 30 * 60
        const newTime = new Date().getTime() / 1000
        //倒计时剩余时间
        let timeDiff = Math.floor(endTime - newTime)
        if (timeDiff < 0) { //订单超时
            that.updateOrder(index, 'status', 'invalid')
        } else { //订单末超时
            // 格式化时间
            const t = that.formatTime(timeDiff)
            // 增加在order中的countdown属性
            that.updateOrder(index, 'countdown', t)
            let myTime = setInterval(() => {
                timeDiff--
                if (timeDiff < 0) { //订单超时
                    that.updateOrder(index, 'status', 'invalid')
                    clearInterval(myTime)
                } else {
                    const t = that.formatTime(timeDiff)
                    // 更新在order中的countdown属性
                    that.updateOrder(index, 'countdown', t)
                }
            }, 1000)
            intervalTime = myTime
            that.updateOrder(index, 'intervalTime', myTime) //保存定时器ID
        }
    },
    //创建websocket客户端
    createSocket(openid, orderid) {
        let ws = wx.connectSocket({
            url: 'ws://localhost:7000/' + openid,
        })
        ws.onOpen(() => {
            console.log('连接cg')
            const data = { identity: openid, msg: orderid }
            ws.send({ data: JSON.stringify(data) })
        })
        ws.onMessage((res) => {
            console.log(res)
            this.onShow()
            wx.showToast({
                title: res,
                icon: 'none'
            })
        })
        setTimeout(() => {
            ws.close({ reason: openid })
            console.log('连接关闭')
        }, 10000)
    },
    // 修改订单属性 并且修改数据库
    async updateOrder(index, field, value) {
        let {
            order
        } = this.data
        if (field === 'status') {
            //修改order数组状态
            order[index].order_status = value
            // 修改数据库中订单状态
            wx.request({
                url: `${config.server}/order/status/update`,
                data: {
                    _id: order[index]._id,
                    order_status: value
                },
                method: 'POST',
                success: res => {
                    console.log(res)
                }
            })
        } else if (field === 'countdown') {
            order[index].countdown = value
        } else if (field === 'intervalTime') {
            order[index].intervalTime = value
        }
        this.setData({
            order
        })
    },
    // 格式化时间
    formatTime(timeDiff) {
        let min = (Math.floor(timeDiff / 60)) < 10 ? '0' + (Math.floor(timeDiff / 60)) : (Math.floor(timeDiff / 60)) //分钟
        let sec = (Math.floor(timeDiff % 60)) < 10 ? '0' + (Math.floor(timeDiff % 60)) : (Math.floor(timeDiff % 60))
        return `${min}:${sec}`
    },
    // 设置页面要显示的信息
    pageInfo(msg) {
        this.setData({
            pageInfo: msg
        })
    },
    tabSelect(e) {
        this.setData({
            TabCur: e.currentTarget.dataset.id,
        })
        this.onShow()
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        const { tabList, TabCur } = this.data
        console.log(tabList[TabCur].statusEN)
        this.getOsByOStatus(tabList[TabCur].statusEN)
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        this.clearTime(intervalTime)
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        this.clearTime(intervalTime)
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})